package com.ynny.chapter04.controller;

import com.ynny.chapter04.dao.UserDao;
import com.ynny.chapter04.dao.UserDaoImpl;
import com.ynny.chapter04.entity.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {


    @Override
    protected void service(HttpServletRequest request,
                           HttpServletResponse response) throws ServletException, IOException {
        String userName = request.getParameter("userName");

        //admin
        String password = request.getParameter("pwd");

        //非空 省略

        //用户名是否注册 校验
        //根据用户名去数据库查询 是否已经存在

        UserDao userDao = new UserDaoImpl();

        User user = userDao.selectUserByUserName(userName);

        //用户名已经存在 注册失败
        if (user != null){
            request.setAttribute("msg","用户名已经存在");
            request.getRequestDispatcher("/register.jsp")
                    .forward(request,response);
        }else {
            //注册用户
            //往user表新增一条数据

            User newUser = new User();

            newUser.setUserName(userName);
            newUser.setPassword(password);

            int i = userDao.insertUser(newUser);

            if (i > 0){
                //重定向 到 登录页面

                response.sendRedirect("/chapter04/login.jsp");

            }

        }
    }
}
